package model.commands.misc;

import java.util.List;
import java.util.Map;
import java.util.Scanner;
import model.Environment;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;


/**
 * A command that is defined by a user.
 * 
 * @author Erick Gonzalez
 */
public class UserDefinedCommand extends Command {
    private Interpreter myInterpreter;
    private Map<String, Integer> myVariables;
    private String myCommandString;
    private List<String> myParameters;

    
    /**
     * 
     * @param interpreter an interpreter
     * @param variables a mapping from variable name to variable value in this scope
     * @param commandString a command string
     * @param parameters a list of parameters
     */
    public UserDefinedCommand(Interpreter interpreter,
                              Map<String, Integer> variables,
                              String commandString,
                              List<String> parameters) {
        myInterpreter = interpreter;
        myVariables = variables;
        myCommandString = commandString;
        myParameters = parameters;
    }

    @Override
    public int evaluate(Environment e) throws SyntaxErrorException {
        List<Command> arguments = getArguments();

        for (int i = 0; i < myParameters.size(); ++i) {
            myVariables.put(myParameters.get(i), arguments.get(i).evaluate(e));
        }

        Scanner s = new Scanner(myCommandString);
        return myInterpreter.parse(s, myVariables).evaluate(e);
    }
}
